import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import 'package:flutter_note/note/base.dart';
import 'package:flutter_note/note/bean.dart';
import 'package:flutter_note/note/const.dart';
import 'package:flutter_note/note/manager.dart';
import 'package:flutter_note/note/utils.dart';
import 'package:flutter_note/note/widgets.dart';

class UserUpdatePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _UserUpdatePageState();
  }
}

class _UserUpdatePageState extends BaseState<UserUpdatePage> {
  User _user = User();
  UserManager _userManager;
  TextEditingController _nameController = TextEditingController();
  TextEditingController _aboutController = TextEditingController();
  File _image;

  @override
  void initState() {
    super.initState();
    _userManager = UserManager.getInstance();
    _user = _userManager.getUser();
    _nameController.text = _user.name;
    _aboutController.text = _user.about;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldkey,
      backgroundColor: color.bg_page,
      appBar: AppBar(
        title: Text('修改信息'),
        elevation: dim.x2,
        actions: <Widget>[
          GestureDetector(
            onTap: () {
              _userModify();
            },
            child: Container(
                color: Colors.transparent,
                width: dim.x60,
                child: Icon(Icons.check)),
          )
        ],
      ),
      body: ListView(
        controller: ScrollController(keepScrollOffset: false),
        children: <Widget>[
          Space(Const.SPACE_TOP),
          _userHead(),
          Space(Const.SPACE_TOP),
          _userName(),
          Space(Const.SPACE_TOP),
          _userAbout(),
        ],
      ),
    );
  }

  Widget _headImage() {
    var size = dim.x60;
    if (_image != null) {
      return Center(
        child: ClipOval(
          child: Image.file(_image, width: size, height: size),
        ),
      );
    } else {
      return Center(
        child: ClipImageView(_user.head, size, size, Const.IMG_SIZE_HEAD),
      );
    }
  }

  Widget _userName() {
    return Container(
      height: dim.x50,
      padding: EdgeInsets.only(left: dim.x15, right: dim.x15),
      child: Row(children: <Widget>[
        Center(
          child: Text(
            '昵称',
            style: TextStyle(
              color: color.txt3,
              fontSize: dim.t16,
            ),
          ),
        ),
        Space(Const.SPACE_LEFT),
        Expanded(
          flex: 1,
          child: Container(
            padding: EdgeInsets.only(left: dim.x15, right: dim.x15),
            decoration: BoxDecoration(
                //borderRadius: BorderRadius.all(Radius.circular(5.0)),
                border: Border.all(color: color.line)),
            alignment: Alignment.centerLeft,
            child: TextField(
              maxLines: 1,
              keyboardType: TextInputType.text,
              controller: _nameController,
              style: TextStyle(fontSize: dim.t16, color: color.txt3),
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: '请输入昵称',
                  hintStyle: TextStyle(fontSize: dim.t16, color: color.txt9)),
            ),
          ),
        ),
      ]),
    );
  }

  Widget _userAbout() {
    return Container(
      padding: EdgeInsets.only(left: dim.x15, right: dim.x15),
      child: Row(
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              height: dim.x50,
              child: Center(
                child: Text(
                  '简介',
                  style: TextStyle(
                    color: color.txt3,
                    fontSize: dim.t16,
                  ),
                ),
              ),
            ),
            Space(Const.SPACE_LEFT),
            Expanded(
              flex: 1,
              child: Container(
                padding: EdgeInsets.only(left: dim.x15, right: dim.x15),
                decoration: BoxDecoration(
                    //borderRadius: BorderRadius.all(Radius.circular(5.0)),
                    border: Border.all(color: color.line)),
                alignment: Alignment.centerLeft,
                child: TextField(
                  maxLines: null,
                  keyboardType: TextInputType.text,
                  controller: _aboutController,
                  style: TextStyle(fontSize: dim.t16, color: color.txt3),
                  decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: '请输入我的简介',
                      hintStyle:
                          TextStyle(fontSize: dim.t16, color: color.txt9)),
                ),
              ),
            ),
          ]),
    );
  }

  Widget _userHead() {
    return Container(
      height: dim.x85,
      padding: EdgeInsets.only(left: dim.x15, right: dim.x15),
      child: Row(
        children: <Widget>[
          Text(
            '头像',
            style: TextStyle(
              color: color.txt3,
              fontSize: dim.t16,
            ),
          ),
          Space(Const.SPACE_LEFT),
          Expanded(
            flex: 1,
            child: Container(
              decoration: BoxDecoration(
                  //borderRadius: BorderRadius.all(Radius.circular(5.0)),
                  border: Border.all(color: color.line)),
              child: RaisedButton(
                color: color.transparent,
                onPressed: () {
                  _pickAndUpload();
                },
                shape: BorderDirectional(),
                elevation: 0.0,
                highlightElevation: 0.0,
                padding: EdgeInsets.all(0.0),
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: Container(
                    width: dim.x85,
                    child: _headImage(),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  //选择图片,并且上传
  _pickAndUpload() async {
    File image = await ImageUtils.pickImage(true); //上传头像,需要剪裁
    if (image == null) {
      showMessage('选择图片失败');
      return;
    }
    Reply reply = await UploadFileManager.getInstance().uploadFile(image);
    setState(() {
      if (reply.code == Const.SUCCESS) {
        _image = image; //上传成功就更新图片
      } else {
        showMessage('上传图片失败');
      }
    });
  }

  //发送修改用户信息
  _userModify() async {
    show();
    String head = _user.head; //默认头像
    if (_image != null) {
      head = _image.path.substring(_image.path.lastIndexOf('/') + 1); //修改后的头像
    }
    Reply reply = await _userManager.userModify(
        _nameController.text, _aboutController.text, head); //请求修改
    dismiss();
    await Future.delayed(Duration(milliseconds: 50), _modifyResult(reply));
  }

  _modifyResult(Reply reply) {
    if (reply.code == Const.SUCCESS) {
      Navigator.of(context).pop(reply); //修改成功,返回到上一页
    } else {
      showMessage('修改用户信息失败'); //修改失败,直接提示
    }
  }
}
